<?php
/**
 * User: 昊天||597767865@qq.com
 * Date: 2019/8/27
 * Time: 17:16
 */
namespace backend\controllers;
use backend\models\Menu;
use backend\models\Role;
use Yii;
class RoleController extends BaseController
{
    public function actionIndex()
    {
        $pageSize = $this->pageSize;
        $moduleId = intval(input('moduleId'));
        return $this->render('index',compact('pageSize','moduleId'));
    }

    /**
     * 列表
     */
    public function actionList()
    {
        $page = intval(input('page'));
        $limit = intval(input('limit'));
        $model = Role::find();
        $data = $model
            ->offset(($page-1)*$limit)
            ->limit($limit)
            ->asArray()->all();
        $count = $model->count();
        $this->api(0,'success',$count,$data);
    }

    public function actionCreate(){
        $menu = Menu::find()->alias('a')->joinWith('route')
            ->where(['a.is_show'=>1])
            ->asArray()->all();
        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            empty($data['ids']) && $this->json(100,'拥有权限不可以为空！');
            unset($data[Yii::$app->request->csrfParam]);
            $data['create_time'] = time();
            $data['create_user'] = Yii::$app->user->identity->name;
            $data['ids'] = array_values(array_map('intval',$data['ids']));
            $data['jurisdiction'] = json_encode($data['ids']);
            $model = new Role();
            $arr['Role'] = $data;
            if($model->load($arr) && $model->save()){
                $this->json(200,'添加角色成功');
            }
            $this->json(100,array_values($model->getFirstErrors())[0]);
        }
        return $this->render('create',compact('menu'));
    }

    public function actionEdit()
    {
        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            unset($data[Yii::$app->request->csrfParam]);
            $id = intval($data['id']);
            $data['ids'] = array_values(array_map('intval',$data['ids']));
            $data['jurisdiction'] = json_encode($data['ids']);
            $model = Role::findOne($id);
            $arr['Role'] = $data;
            if($model->load($arr) && $model->save()){
                $this->json(200,'角色编辑成功');
            }
            $this->json(100,array_values($model->getFirstErrors())[0]);
        }
        $id = intval(input('id'));
        $model = Role::findOne($id);
        $menu = Menu::find()->alias('a')->joinWith('route')
            ->where(['a.is_show'=>1])
            ->asArray()->all();
        return $this->render('edit',compact('model','menu'));
    }
}
